package com.ooula.customcalendarview.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ooula.customcalendarview.R;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2017/5/17.
 */

public class NewCalendar extends LinearLayout {
    private ImageView ivPrev;
    private ImageView ivNext;
    private TextView tv_date;
    private GridView calendar_grid;
    private String displayFormat;
    public NewCalendarListener listener;
    public NewCalendarOnClickListener calendarOnClickListener;

    private Calendar curDate = Calendar.getInstance();

    public NewCalendar(Context context) {
        super(context);
    }

    public NewCalendar(Context context, AttributeSet attrs) {
        super(context, attrs);
        initControl(context, attrs);
        renderCalendar();
    }

    public NewCalendar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initControl(context, attrs);
        renderCalendar();
    }

    /**
     * 初始化
     *
     * @param context
     */
    private void initControl(Context context, AttributeSet attrs) {
        bindControl(context);
        bindControlEvent();
        TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.NewCalendar);
        try {
            String format = ta.getString(R.styleable.NewCalendar_dataFormat);
            displayFormat = format;
            if (displayFormat == null) {
                displayFormat = "MMM yyyy";
            }
        } finally {
            ta.recycle();
        }
        renderCalendar();

    }

    /**
     * 事件绑定
     */
    private void bindControlEvent() {
        ivPrev.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                curDate.add(Calendar.MONTH, -1);
                renderCalendar();
            }
        });

        ivNext.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                curDate.add(Calendar.MONTH, 1);
                renderCalendar();
            }
        });
    }

    private void bindControl(Context context) {
        LayoutInflater inflater = LayoutInflater.from(context);
        inflater.inflate(R.layout.calendar_view, this);
        ivNext = (ImageView) findViewById(R.id.ivNext);
        ivPrev = (ImageView) findViewById(R.id.ivPrev);
        tv_date = (TextView) findViewById(R.id.tv_date);
        calendar_grid = (GridView) findViewById(R.id.calendar_grid);
        calendar_grid.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                if (listener == null) {
                    return false;
                } else {
                    listener.onItemLongPress((Date) parent.getItemAtPosition(position));
                    return true;
                }
            }
        });

        calendar_grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    calendarOnClickListener.onItemOnClickListener((Date) parent.getItemAtPosition(position));
            }
        });
    }

    /**
     * 日历绘制
     */
    private void renderCalendar() {
        SimpleDateFormat sdf = new SimpleDateFormat(displayFormat);
        tv_date.setText(sdf.format(curDate.getTime()));

        List<Date> cells = new ArrayList<>();
        //复制当前日期
        Calendar calendar = (Calendar) curDate.clone();
        //设置当前日历为当月的第一天
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        //计算本月前一个月的天数
        int prevDays = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        //日历向前prevDays天
        calendar.add(Calendar.DAY_OF_MONTH, -prevDays);
        //日历最多六行显示
        int maxCellCount = 6 * 7;
        while (cells.size() < maxCellCount) {
            cells.add(calendar.getTime());
            //向后一天
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }

        calendar_grid.setAdapter(new CalenderAdapter(getContext(), cells));
    }

    private class CalenderAdapter extends ArrayAdapter<Date> {
        LayoutInflater inflater;

        public CalenderAdapter(Context context, List<Date> list) {
            super(context, R.layout.calender_text_days, list);
            inflater = LayoutInflater.from(context);
        }

        @NonNull
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Date date = getItem(position);
            Date now = new Date();
            boolean isTheSeamMonth = false;

            if (convertView == null) {
                convertView = inflater.inflate(R.layout.calender_text_days, parent, false);
            }
            int days = date.getDate();
            ((TextView) convertView).setText(String.valueOf(days));


            if (date.getMonth() == now.getMonth()) {
                isTheSeamMonth = true;
            }
            if (isTheSeamMonth) {
                //设置当前月的字体色
                ((TextView) convertView).setTextColor(Color.parseColor("#000000"));
            } else {
                //设置非当前月的字体色
                ((TextView) convertView).setTextColor(Color.parseColor("#666666"));
            }
            //当天日期用红色字体和边框突出
            if (date.getMonth() == now.getMonth() && date.getDate() == now.getDate() && date.getYear() == now.getYear()) {
                ((TextView) convertView).setTextColor(Color.parseColor("#ff0000"));
                ((NewCalenderText) convertView).isToday = true;
            }
            return convertView;
        }
    }

    public interface NewCalendarListener {
        void onItemLongPress(Date data);
    }

    public interface NewCalendarOnClickListener {
        void onItemOnClickListener(Date date);
    }
}
